package com.app.business.service;

import com.app.business.calculate.CalculateHandInMoneyUtils;
import com.app.business.model.Contract;
import com.app.business.model.HandInMoney;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.permission.model.UserInfo;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.google.common.collect.Maps;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ddz on 2019/6/10.
 */
@Service
@Transactional
@SuppressWarnings("all")
public class HandInMoneyService extends JpaBaseDao<HandInMoney, Integer> {

    @Autowired
    private ContractService contractService;
    @Autowired
    private ActionHistoryService actionHistoryService;

    /**
     * 根据协议Id得到缴款记录
     *
     * @param contractId
     * @return
     */
    public List<HandInMoney> getHandInMoneyListByContractId(Integer contractId) {
        //查询语句
        String hql = " from HandInMoney m where m.contract.id = :contractId order by m.handInMoneyDate";
        Map<String, Object> map = new HashMap<>();
        map.put("contractId", contractId);
        return this.findHql(hql, map);
    }

    /**
     * 缴款记录保存
     *
     * @param request
     * @return
     */
    public synchronized Response handInMoneySave(HttpServletRequest request) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        UserInfo userInfo = WebUtils.getLoginUserInfo();
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        Integer handInMoneyId = ParamUtils.getInt(request, "handInMoneyId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");
        HandInMoney handInMoney = this.findOne(handInMoneyId);
        handInMoney = handInMoney == null ? new HandInMoney() : handInMoney;
        WebUtils.bind(request, handInMoney);
        handInMoney.setContract(contract);
        handInMoney.setHandInMoneyPerson(userInfo.getName());
        this.save(handInMoney);
        this.actionHistoryService.saveActionHistoryByContractId(contract.getId(), "缴款记录保存", "缴款记录保存");

        CalculateHandInMoneyUtils.main(contract.getId());
        return new Response("0001", "保存成功！");
    }

    public Map<String, Map> getYjkInfoMap() {
        StringBuffer sql = new StringBuffer("SELECT h.contract_id AS 'contractId', ");
        sql.append("SUM(CASE WHEN h.hand_in_money_type = 1 THEN IFNULL(h.hand_in_money,0) ELSE 0 END) AS 'ybjFee', ");
        sql.append("SUM(CASE WHEN h.hand_in_money_type = 2 THEN IFNULL(h.hand_in_money,0) ELSE 0 END) AS 'bdGwjFee', ");
        sql.append("SUM(CASE WHEN h.hand_in_money_type = 3 THEN IFNULL(h.hand_in_money,0) ELSE 0 END) AS 'jfGwjFee', ");
        sql.append("SUM(IFNULL(h.hand_in_money,0)) AS 'yjTotalFee' ");
        sql.append("FROM hand_in_money h ");
        sql.append("GROUP BY h.contract_id ");
        List<Map> mapList = this.entityManager.createNativeQuery(sql.toString())
                .unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        Map<String, Map> resultMap = Maps.newLinkedHashMap();
        if (CollectionUtils.isNotEmpty(mapList)) {
            for (Map map : mapList) {
                String contractId = map.get("contractId").toString();
                resultMap.put(contractId,map);
            }
        }
        return resultMap;
    }

}
